<?php
namespace Modules\Activity\Http\Controllers\Admin\Leitai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Leitai\Activity;

use Validator;
use ThrowException;
use DB;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $options = $req->all();

        $per_page = 100;
        if ( isset($options['per_page']) && $options['per_page'] > 0 ){
            $per_page = $options['per_page'];
        }

        $page = 0;
        if ( isset($options['page']) && $options['page'] > 0 ){
            $page = $options['page']-1;
        }

        $offset = $page * $per_page;

        $where = '1';
        if ( isset($options['status']) && $options['status'] == 'sell_out' ){
            $where .= " and stock = 0 AND status = 1 ";
        }
        if ( isset($options['status']) && $options['status'] == 'off_stock' ){
            $where .= " and status = 0 ";
        }
        if ( isset($options['status']) && $options['status'] == 'on_stock' ){
            $where .= " and (stock > 0 or stock is null) AND status = 1 ";
        }

        if ( isset($options['key']) && $options['key'] ){
            $where .= " and title like '%{$options['key']}%' ";
        }

        if ( isset($options['ids']) && $options['ids'] ){
            $where .= " and title IN (select title from leitai_activity where id in (".implode(',', $options['ids']).") ) ";
        }

        $sql = "SELECT * FROM leitai_data_sum WHERE $where ORDER BY list_weight DESC, created_at DESC LIMIT $per_page OFFSET $offset";
        $res = DB::select($sql);


        $total_res = DB::select(" select count(*) cnt from leitai_data_sum WHERE $where ");

        if ( count($res) == 0 ){
            $res_ = [
                'current_page' => $page,
                'item_total' => 1,
                'list' => [],
            ];
        }else{
            $total_res = object_to_array($total_res);

            $res = object_to_array($res);
            $res_ = [
                'current_page' => $page+1,
                'item_total' => $total_res[0]['cnt'],
                'list' => $res,
            ];
        }

        return json_encode($res_);

        /*
        $rule = [
            // 'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        $options['order_by'] = ['list_weight' => 'desc'];
        $options['with_count'] = ['skus', 'last_skus'];
//        $options['with'] = ['Leitai_last_skus'];

        $list = Activity::getList($options);

        $list->each(function ($item) {
            $item->sku_stock = $item->skus->sum('stock');
            $item->last_sku_stock = $item->last_skus->sum('stock');
        });

        return $list->generateListResponse();
        */
    }

    public function getCnt(Request $req)
    {
        $options = $req->all();
        $w = '';
        if ( isset($options['key']) && $options['key'] ){
            $w = " and title like '%{$options['key']}%' ";
        }

        $total = ['on_stock'=>0, 'off_stock'=>0, 'sell_out'=>0];
        $res = DB::select("select stock, status from leitai_data_sum where 1 $w ");
        foreach ( $res as $v ){
            if ( $v->status == 1 ){
                if ( $v->stock === 0 ){
                    $total['sell_out']++;
                }else{
                    $total['on_stock']++;
                }
            }else{
                $total['off_stock']++;
            }
        }

        return [
            'total' => $total
        ];
    }

    public function getList(Request $req)
    {
        $options = $req->all();

        $options['with_count'] = ['skus', 'last_skus'];
//        $options['with'] = ['Leitai_last_skus'];
        $options['order_by'] = ['list_weight' => 'desc'];

        if ( isset($options['title']) && $options['title'] ){
            $options['where'] = ['title' => $options['title']];
        }

        $list = Activity::getList($options);

        $list->each(function ($item) {
            $item->sku_stock = $item->skus->sum('stock');
            $item->last_sku_stock = $item->last_skus->sum('stock');
        });

        return $list->generateListResponse();
    }


    public function show(Request $req, $uuid)
    {
        //
        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'title' =>  ['required'],
            'stock' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $info = $req->all();

        DB::beginTransaction();

        $item = Activity::create($info);

        DB::commit();

        $sql = "SELECT
                    title,
                    money_price,
                    score_price,
                    max( id ) id,
                    max( uuid ) uuid,
                    max( open_value ) open_value,
                    count( id ) cnt,
                    min( created_at ) created_at,
                    min( thumb ) thumb,
                    status,
                    play_type,
                    max( list_weight ) list_weight,
                    max(is_invite_enabled) is_invite_enabled,
                    max(is_share_enabled) is_share_enabled
                FROM
                    leitai_activity
                WHERE
                    title = '{$info['title']}'
                GROUP BY
                    title,
                    money_price,
                    score_price,
                    play_type,
                    STATUS ";

        $res = DB::select($sql);

        if ( $res ){
            foreach ( $res as &$v ){
                $v->create_time = date('Y-m-d H:i:s');
                $v->stock = 0;
                $v->sales = 0;
                $stock_res_id = DB::table('leitai_activity')->where('title', $v->title)->get('id')->toArray();
                $ids = array_column($stock_res_id, 'id');

                $stock_res = DB::table('leitai_skus')->whereIN('activity_id', $ids)->get(\DB::raw('sum(stock) stock, sum(sales) sales'))->first();
                unset($ids);
                if ( $stock_res ){
                    $v->stock = $stock_res->stock;
                    $v->sales = $stock_res->sales;
                }
            }
            $res = object_to_array($res);
            DB::table("leitai_data_sum")->insert($res);
        }

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            $item->update($info);
        }elseif ($req->type === 'copy') {
            $item->copy();
        }

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }

    public function doPatch(Request $req, $type)
    {
        $options = $req->all();
        $title = $options['title'];

        if ( $type == 'update' ){
            $title = $options['title_old'];
            $arr = [
                'title',
                'thumb',
                'image_3d',
                'money_price',
                'score_price',
                'stock',
                'sales',
                'rules',
                'status',
                'play_type',
                'node_1',
                'node_2',
                'run_time',
                'open_value',
                'last_open_time',
                'last_open_time_set',
                'list_weight',
                'share_rule',
                'is_share_enabled',
                'is_invite_enabled',
                'invite_rule',
            ];

            $arr2 = [
                'title',
                'thumb',
                'money_price',
                'score_price',
                'status',
                'play_type',
                'list_weight',
                'run_time',
                'is_share_enabled',
                'is_invite_enabled'
            ];
            $options2 = [];
            foreach ( $options as $k => $v ){
                if ( !in_array($k, $arr) ) unset($options[$k]);
                if ( in_array($k, $arr2) ){
                    $options2[$k] = $v;
                }
                if ( in_array($k, ['is_share_enabled', 'is_invite_enabled']) ){
                    $options[$k] = in_array($v, ['false', '0']) ? 0 : 1;
                    $options2[$k] = in_array($v, ['false', '0']) ? 0 : 1;
                }
            }
            DB::table('leitai_data_sum')->where('title', '=', $title)->update($options2);
            DB::table('leitai_activity')->where('title', '=', $title)->update($options);

            $act = DB::table('leitai_activity')->where('title', $options['title'])->first('run_time');

            /*
            $item_r = DB::table('leitai_cron_skus')->where('title', $title)->first();
            if ( $act->run_time ){
                $run_tim = explode('-', $act->run_time);
                $arr_new = [
                    'title' => $options['title'],
                    'start_time' => $run_tim[0],
                    'end_time' => $run_tim[1],
                    'run_time' => $run_tim[2],
                ];
                if ( $item_r ){
                    DB::table('leitai_cron_skus')->where('title', '=', $title)->update($arr_new);
                }else{
                    $arr_new['title'] = $options['title'];
                    $arr_new['play_type'] = $options['play_type'];
                    DB::table('leitai_cron_skus')->insert($arr_new);
                }
            }else{
                if ( $item_r ){
                    DB::table('leitai_cron_skus')->where('title', '=', $title)->delete();
                }
            }
            */

        }
        if ( $type == 'delete' ){
            DB::table('leitai_activity')->where('title', '=', $title)->delete();

            DB::delete('DELETE FROM `leitai_last_skus` WHERE activity_id NOT IN (SELECT id FROM leitai_activity)');
            DB::delete('DELETE FROM `leitai_skus` WHERE activity_id NOT IN (SELECT id FROM leitai_activity)');
            DB::delete('DELETE FROM `choushang_last_skus` WHERE activity_id NOT IN (SELECT id FROM choushang_activity)');
            DB::delete('DELETE FROM `choushang_skus` WHERE activity_id NOT IN (SELECT id FROM choushang_activity)');
        }
        return [];
    }

    public function off_stock_all()
    {
        DB::beginTransaction();
        DB::table('leitai_activity')->update(['status'=>0]);
        DB::commit();

        return [];
    }

    public function copy_more(Request $req, $uuid)
    {
        ini_set("memory_limit",'-1');
        ini_set('max_execution_time', 600);
        set_time_limit(0);
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        while (1){
            if ( $req->nums <= 0 ) break;
            $nums = min($req->nums, 20);
            self::copy_more_($uuid, $nums);
            $req->nums -= 20;
        }

        return [];
    }

    public function copy_more_($uuid, $nums)
    {
        DB::beginTransaction();

        $item_r = DB::table('leitai_activity')->where('uuid', $uuid)->first();
        $uuid_arr = array();
        $act_init = object_to_array($item_r);
        $act_init['stock'] += $act_init['sales'];
        $act_init['sales'] = 0;
        $act_arr = array();
        $time = date('Y-m-d H:i:s');

        for ( $i=0; $i<$nums; $i++ ){
            $a_uuid = uniqid();
            array_push($uuid_arr, $a_uuid);
            $act_arr[$i] = $act_init;
            $act_arr[$i]['uuid'] = $a_uuid;
            $act_arr[$i]['created_at'] = $time;
            $act_arr[$i]['updated_at'] = $time;
            unset($act_arr[$i]['id']);
        }
        DB::table('leitai_activity')->insert($act_arr);

        $id_obj = DB::table('leitai_activity')->whereIn('uuid', $uuid_arr)->get()->toArray();
        $id_arr = array_column($id_obj, 'id');

        $sku_r = DB::table('leitai_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['stock'] = $sv->sales + $sv->stock;
                $sku_arr[$index_sku]['sales'] = 0;
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }
        DB::table('leitai_skus')->insert($sku_arr);
        unset($sku_arr);
        unset($sku_r);

        $sku_r = DB::table('leitai_last_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['stock'] = $sv->sales + $sv->stock;
                $sku_arr[$index_sku]['sales'] = 0;
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }

        DB::table('leitai_last_skus')->insert($sku_arr);
        unset($sku_arr);
        unset($sku_r);
        DB::commit();

        return true;
    }


    public function copy_more_old(Request $req, $uuid)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo([
            'image_3d',
            'invite_rule',
            'is_invite_enabled',
            'min_lucky_score',
            'money_price',
            'multi_buy_discount',
            'tags',
            'thumb',
            'title',
            'stock',
            'play_type',
            'open_value',
            'rules',
            'node_1',
            'node_2',
            'last_open_time_set',
            'sku_level'
        ]);

        if ( $req->nums > 0 ){
            $newItem = Activity::create($info);
            $skuArray = [];

            $stock = array();
            foreach ($item->skus as $sku) {
                if ( !isset($stock[$sku->title]) ){
                    $stock[$sku->title] = $sku->stock + $sku->sales;
                }

                $skuInfo = $sku->getInfo([
                    'activity_id',
                    'sku_type',
                    'assets',
                    'product_id',
                    'title',
                    'number',
                    'thumb',
                    'money_price',
                    'score_price',
                    'stock',
                    'odds',
                    'level',
                    'list_weight',
                    'status',
                    'is_resaleable',
                    'display_money_price',
                    'discount_score_price',
                    'detail_images',
                    'return_sale_ratio',
                    'use_lucky_score'
                ]);
                $skuInfo['stock'] = $stock[$sku->title];
                $skuInfo['uuid'] = uniqid();

                array_unshift($skuArray, $skuInfo);
            }

            $lastSkuArray = [];
            $last_stock = array();
            foreach ($item->last_skus as $sku) {
                if ( !isset($last_stock[$sku->title]) ){
                    $last_stock[$sku->title] = $sku->stock + $sku->sales;
                }
                $lastSkuInfo = $sku->getInfo([
                    'activity_id',
                    'sku_type',
                    'assets',
                    'product_id',
                    'title',
                    'number',
                    'thumb',
                    'money_price',
                    'score_price',
                    'stock',
                    'odds',
                    'level',
                    'list_weight',
                    'status',
                    'is_resaleable',
                    'display_money_price',
                    'discount_score_price',
                    'detail_images',
                    'return_sale_ratio',
                    'last_prize_type',
                    'show_to',
                    'more_value1',
                    'more_value2',
                    'kong_value',
                    'use_lucky_score'
                ]);
                $lastSkuInfo['stock'] = $last_stock[$sku->title];
                $lastSkuInfo['uuid'] = uniqid();

                array_unshift($lastSkuArray, $lastSkuInfo);
            }


            for ( $i=0; $i<$req->nums; $i++ ){
                $newItem = Activity::create($info);
                $skuArray = [];

                $stock = array();
                foreach ($item->skus as $sku) {
                    if ( !isset($stock[$sku->title]) ){
                        $stock[$sku->title] = $sku->stock + $sku->sales;
                    }

                    $skuInfo = $sku->getInfo([
                        'activity_id',
                        'sku_type',
                        'assets',
                        'product_id',
                        'title',
                        'number',
                        'thumb',
                        'money_price',
                        'score_price',
                        'stock',
                        'odds',
                        'level',
                        'list_weight',
                        'status',
                        'is_resaleable',
                        'display_money_price',
                        'discount_score_price',
                        'detail_images',
                        'return_sale_ratio',
                        'use_lucky_score'
                    ]);
                    $skuInfo['stock'] = $stock[$sku->title];
                    $skuInfo['uuid'] = uniqid();

                    array_unshift($skuArray, $skuInfo);
                }

                $lastSkuArray = [];
                $last_stock = array();
                foreach ($item->last_skus as $sku) {
                    if ( !isset($last_stock[$sku->title]) ){
                        $last_stock[$sku->title] = $sku->stock + $sku->sales;
                    }
                    $lastSkuInfo = $sku->getInfo([
                        'activity_id',
                        'sku_type',
                        'assets',
                        'product_id',
                        'title',
                        'number',
                        'thumb',
                        'money_price',
                        'score_price',
                        'stock',
                        'odds',
                        'level',
                        'list_weight',
                        'status',
                        'is_resaleable',
                        'display_money_price',
                        'discount_score_price',
                        'detail_images',
                        'return_sale_ratio',
                        'last_prize_type',
                        'show_to',
                        'more_value1',
                        'more_value2',
                        'kong_value',
                        'use_lucky_score'
                    ]);
                    $lastSkuInfo['stock'] = $last_stock[$sku->title];
                    $lastSkuInfo['uuid'] = uniqid();

                    array_unshift($lastSkuArray, $lastSkuInfo);
                }

                $newItem->skus()->createMany($skuArray);
                $newItem->last_skus()->createMany($lastSkuArray);
            }
        }

        return [];
    }

    public function copy_one(Request $req, $uuid)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo([
            'image_3d',
            'invite_rule',
            'is_invite_enabled',
            'min_lucky_score',
            'money_price',
            'multi_buy_discount',
            'tags',
            'thumb',
            'title',
            'stock',
            'play_type',
            'open_value',
            'rules',
            'node_1',
            'node_2',
            'run_time',
            'last_open_time_set',
            'sku_level'
        ]);
        $info['status'] = 0;
        $info['title'] .= '-副本';

        $newItem = Activity::create($info);
        $skuArray = [];
        foreach ($item->skus as $sku) {
            $sku->stock = $sku->stock + $sku->sales;

            $skuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'use_lucky_score'
            ]);

            $skuInfo['uuid'] = uniqid();

            array_unshift($skuArray, $skuInfo);
        }

        $lastSkuArray = [];
        foreach ($item->last_skus as $sku) {
            $sku->stock = $sku->stock + $sku->sales;

            $lastSkuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'last_prize_type',
                'more_value1',
                'more_value2',
                'kong_value',
                'show_to',
                'use_lucky_score'
            ]);

            $lastSkuInfo['uuid'] = uniqid();

            array_unshift($lastSkuArray, $lastSkuInfo);
        }

        $newItem->skus()->createMany($skuArray);
        $newItem->last_skus()->createMany($lastSkuArray);

        return [];
    }


}
